<template>
  <div class="form-container">
    <el-form inline :model="form" ref="ruleForm" class="form-line" label-width="90">
      <el-form-item label="编号/车牌号" prop="vehicleId">
        <el-input size="default" v-model="form.vehicleId" placeholder="编号/车牌号"></el-input>
      </el-form-item>
      <el-form-item label="车辆类型" prop="vehicleType">
        <el-select v-model="form.vehicleType" placeholder="请选择车辆类型">
          <el-option v-for="item in TypeList" :key="item.id" :label="item.typeName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div class="btn-container">
      <el-button type="primary" @click="handleReset(ruleForm as FormInstance)">重置</el-button>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button type="primary" @click="handleAdd">添加</el-button>
    </div>
  </div>
  <div class="table-container">
    <el-table
      border
      :cell-style="{ textAlign: 'center', fontSize: '13px' }"
      :header-cell-style="{
        textAlign: 'center',
        fontWeight: '100',
        fontSize: '13px',
        color: 'white',
        backgroundColor: '#009688'
      }"
      :data="tableData"
      style="width: 100%"
    >
      <el-table-column fixed prop="userName" label="车辆编号/车牌号" width="300">
        <template #default="scope">
          {{ scope.row.vehicleId + "/" + scope.row.vehicleNumber }}
        </template>
      </el-table-column>
      <el-table-column prop="typeName" label="车辆类型" />
      <el-table-column prop="companyName" label="所属公司" />
      <el-table-column prop="driverLicenseTypeName" label="所属驾驶证类型" />
      <el-table-column prop="vehicleStatus" label="状态">
        <template #default="scope">
          <span v-if="scope.row.vehicleStatus == '1'">正常</span>
          <span v-else-if="scope.row.vehicleStatus == '2'">维修中</span>
          <span v-else-if="scope.row.vehicleStatus === '3'">报废</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="250">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
          <el-button link type="primary" size="small" @click="handleEdit(scope.row.id)"> 查看详情 </el-button>
          <el-button link type="primary" size="small" @click="handleUpdate(scope.row)"> 修改 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        background
        size="small"
        v-model:current-page="form.pageNum"
        :page-sizes="[5, 10, 15, 20]"
        layout="prev, pager, next"
        :total="pageTotal"
        @change="getCarList"
        :page-size="form.pageSize"
      />
    </div>
  </div>
  <el-dialog v-model="centerDialogVisible" :title="titleMsg" width="500" center>
    <div>
      <el-form :model="addForm" ref="refPhoneForm" :rules="addFormRules" label-width="100">
        <el-form-item prop="vehicleId" label="车辆编号">
          <el-input disabled v-model="addForm.vehicleId" placeholder="系统生成"></el-input>
        </el-form-item>
        <el-form-item prop="vehicleIdentificationNumber" label="车架号">
          <el-input v-model="addForm.vehicleIdentificationNumber" placeholder="请填写车架号"></el-input>
        </el-form-item>
        <el-form-item prop="vehicleNumber" label="车牌号">
          <el-input v-model="addForm.vehicleNumber" placeholder="请填写车牌号"></el-input>
        </el-form-item>
        <el-form-item prop="vehicleType" label="车辆类型">
          <el-select v-model="addForm.vehicleType" placeholder="请选择车辆类型">
            <el-option v-for="item in TypeList" :key="item.id" :label="item.typeName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="company" label="所属公司">
          <el-select v-model="addForm.company" placeholder="请选择所属公司">
            <el-option
              v-for="item in companyList"
              :key="item.companyId"
              :label="item.companyName"
              :value="item.companyId"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpdateSubmit(refPhoneForm as FormInstance)"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="tsx" name="useProTable">
import { ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus";
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { getCarListAPI, CarDeleteAPI, upadateCarAPI, addCarAPI, getCarTypeListAPI } from "@/api/modules/province/carManageAPI";
import { CarManage, CarType } from "@/api/interface/province/carManage";
import { Company } from "@/api/interface/province/organizationManage";
import { getCompanyListAPI } from "@/api/modules/province/organizMangeAPI";
const router = useRouter();
//ProCompanyType 已经通过declare全局申明过不用再单独导入
let tableData = ref<CarManage.Row[]>([]);
let pageTotal = ref<number>(0);
let centerDialogVisible = ref<boolean>(false);
const titleMsg = ref<string>("添加");
const form = ref<CarManage.SearchParams>({
  vehicleId: "",
  vehicleType: "",
  pageNum: 1,
  pageSize: 10
});
const addForm = ref<CarManage.Update>({
  vehicleIdentificationNumber: "",
  vehicleNumber: ""
});
const ruleForm = ref<FormInstance>();
const refPhoneForm = ref<FormInstance>();
const addFormRules = ref<FormRules>({
  vehicleType: [{ required: true, message: "请选择车辆类型", trigger: "change" }],
  vehicleIdentificationNumber: [{ required: true, message: "请填写车架号", trigger: "blur" }]
});
const handleEdit = (id: string) => {
  router.push({
    path: "/provinceLevel/proCar/proCarManage/detail",
    query: { id }
  });
};
const handleReset = (Elform: FormInstance) => {
  Elform.resetFields();
};

const handleSearch = (): void => {
  getCarList();
};
const handleAdd = (): void => {
  addForm.value = {
    vehicleIdentificationNumber: "",
    vehicleNumber: ""
  };
  centerDialogVisible.value = true;
  titleMsg.value = "添加";
};
const handleDelete = (id: number): void => {
  ElMessageBox.confirm(`确定删除该条记录吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      deleteCar(id);
      getCarList();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除"
      });
    });
};
// 删除仓站
const deleteCar = async (id: number) => {
  const { code, msg } = await CarDeleteAPI(id);
  if (code == "200") {
    ElMessage({
      type: "success",
      message: "删除成功!"
    });
  } else {
    ElMessage.error(`删除失败,${msg}`);
  }
};
// 列表接口请求地址
const getCarList = async () => {
  const { rows, total, code, msg } = await getCarListAPI(form.value);
  console.log(total, code);
  if (code == "200" && rows) {
    tableData.value = rows;
    if (total) pageTotal.value = total;
  } else {
    ElMessage.error(`获取列表失败,${msg}`);
  }
};
const handleUpdate = (row: CarManage.Row): void => {
  // addForm.value = row;
  Object.assign(addForm.value, {
    id: row.id,
    vehicleType: row.vehicleType,
    vehicleId: row.vehicleId,
    vehicleIdentificationNumber: row.vehicleIdentificationNumber,
    vehicleNumber: row.vehicleNumber,
    company: row.company
  });
  titleMsg.value = "修改";
  centerDialogVisible.value = true;
};
const handleUpdateSubmit = (elForm: FormInstance) => {
  elForm.validate((valid: boolean) => {
    if (valid) {
      console.log(addForm.value);
      // 发送请求
      if (titleMsg.value == "添加") {
        addCar();
      } else {
        updateCar();
      }
    } else {
      ElMessage.error("请检查输入项");
    }
  });
};
const updateCar = async () => {
  const { code, msg } = await upadateCarAPI(addForm.value);
  if (code == "200") {
    ElMessage({
      type: "success",
      message: "修改成功!"
    });
    centerDialogVisible.value = false;
    getCarList();
  } else {
    ElMessage.error(`修改失败,${msg}`);
  }
};
const addCar = async () => {
  const { code, msg } = await addCarAPI(addForm.value);
  if (code == "200") {
    ElMessage({
      type: "success",
      message: "修改成功!"
    });
    centerDialogVisible.value = false;
    getCarList();
  } else {
    ElMessage.error(`修改失败,${msg}`);
  }
};
let TypeList = ref<CarType.Row[]>([]);
const getCarTypeList = async () => {
  const { rows, code, msg } = await getCarTypeListAPI({
    pageNum: 1,
    pageSize: 10000,
    typeName: ""
  });
  if (code == "200" && rows) {
    TypeList.value = rows;
  } else {
    ElMessage.error(msg);
  }
};
const companyList = ref<Company.CompanyList[]>([]);
const getCompanyList = async () => {
  const { rows, code, msg, total } = await getCompanyListAPI({
    companyName: "",
    city: "",
    pageNum: 1,
    pageSize: 10,
    userId: JSON.parse(localStorage.getItem("userInfo") as string)?.userId
  });
  if (code == "200" && rows && total) {
    companyList.value = rows;
  } else {
    ElMessage.error(msg);
  }
};
onMounted(() => {
  getCarList();
  getCarTypeList();
  getCompanyList();
});
</script>
<style lang="scss" scoped>
.form-container {
  padding: 10px;
  margin-bottom: 10px;
  background-color: white;
  .btn-container {
    display: inline-block;
    float: right;
    vertical-align: middle;
  }
  .el-form {
    display: inline-block;
  }
  .form-line {
    .el-form-item {
      width: 260px;
      margin: 0;
      margin-right: 20px;
    }
    .el-input {
      width: 240px;
    }
    .el-select {
      width: 240px;
    }
  }
}
.table-container {
  padding: 40px 10px;
  padding-bottom: 60px;
  background-color: white;
  .pagination-container {
    // display: inline-block;
    float: right;
    margin-top: 20px;
    background-color: white;
  }
}
::v-deep .el-form-item__label {
  font-size: 13px;
}
::v-deep .el-button > span {
  font-size: 13px;
}
::v-deep .el-input__inner {
  font-size: 13px;
}
</style>
